var ua = window.navigator.userAgent.toLowerCase();
var voice,server;
var userData_ = {};
var code;
var otherVoice = [];
var countNum; //抽奖次数
//判断微信客户端
function isWeiXin() {
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

//判断QQ客户端
function isQQ() {
    if (ua.match(/\sQQ/i) == "qq") {
        return true;
    } else {
        return false;
    }
}

//判断IOS
function isIos() {
    return /iphone|ipod|ipad/i.test(ua);
}

//判断安卓
function isAndroid() {
    return /android/i.test(ua);
}

//查询url字符串
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null;
};
//阻止默认事件
function cancelEvent(event){
window.event? window.event.returnValue = false : event.preventDefault();
}

//阻止事件冒泡
function stopBubble(){
window.event? window.event.cancelBubble = true : e.stopPropagation();
}

//弹窗提示封装
function hintModal(content){
    var text = '<span>' + content + '</span>';
    $('.modal-box').show();
    $('.modal-content').empty().append(text)
}

//上树动效
function treeAnimationUp(){
    $('.animation-box').animate({
        bottom:0
    },3000,function(){
        getGift();
        $('#draw-lottery').show();
        $('#talkBtn').hide();
    });
    $('.bubble6').animate({
        bottom: '30rem'
    },3000);
    $('.bubble2').animate({
        bottom: '22rem'
    },3000);
    $('.bubble5').animate({
        bottom: '16rem'
    },3000);

    $('.bubble1').animate({
        bottom: '37rem',
    },3000);

    $('.bubble3').animate({
        bottom: '14rem'
    },3000);

    $('.bubble4').animate({
        bottom: '24rem'
    },3000);
};
//抽取奖品
function getGift(){
    $.ajax({
        type:'get',
        url:'http://wxapi.ngrok.xiaomiqiu.cn/open/get_prize',
        data:{
            unionId:userData_.unionId,
        },
        success:function(res){
            console.log('奖品:',res,'抽奖次数',countNum,userData_);
            if(res.message == '成功'){
                countNum = countNum - 1;
                $('.modal-box').show();
                $('#chance-num').find('span').html(countNum);
                var myGift = res.data.prizeValue == 0 ? ('<div>' + res.data.prizeName  + '</div>') : ('<div>往往' + res.data.prizeName + res.data.prizeValue + '</div>');
                $('#get-gift').empty().append(myGift);
            }else{
                alert(res.message);
            }
        }
    })
}

//上传录音
function uploadVoice(){
    wx.uploadVoice({
        localId: voice, // 需要上传的音频的本地ID，由stopRecord接口获得
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: function (res) {
            console.log('上传录音返回结果',res);
            server = res.serverId;
            $.ajax({
                type:'get',
                async: false,
                url:'http://wxapi.ngrok.xiaomiqiu.cn/open/save_voice',
                data:{
                    unionId:userData_.unionId,
                    voiceId:res.serverId,
                },
                success:function(res){
                    if(res.message == '成功'){
                        console.log('上传成功！');
                        treeAnimationUp();
                    }else{
                        alert(res.message);
                    }
                }
            });
        }
    });
};
$(window).resize(function () {
   if (window.orientation == 90 || window.orientation == -90) {
        $('#errorScreen').show();
    }else{
        $('#errorScreen').hide();
    }

});

(function(){
    //获取用户信息
    var code_ = GetQueryString('code');
    $.ajax({
        url:'http://wxapi.ngrok.xiaomiqiu.cn/open/userInfo?code=' + code_,
        type:'get',
        success: function(res){
            var userData = res.data;
            if(!userData.id){
                window.location.href = 'http://wxweb.ngrok.xiaomiqiu.cn/';
            };
            $('#chance-num').find('span').html(userData.todayLotteryNum);
            $('.current-user-head').attr('src',userData.headImgUrl);
            console.log('userData',userData);
            userData_ = userData;
            countNum = userData_.todayLotteryNum;

            if(!!GetQueryString('unionId')){
                console.log('分享加一!')
                $.ajax({
                    url:'http://wxapi.ngrok.xiaomiqiu.cn/open/share_add_one?selfUnionId=' + GetQueryString('unionId') + '&unionId=' + userData_.unionId,
                    type:'get',
                    success:function(res){
                        console.log('加一结果:',res);
                    }
                });
            }
        }
    });
})();

//分享传参
(function(){
    var wxShareConfig = {
        imgUrl:userData_.headImgUrl,
        title: "今年圣诞，我想让你知道",
        link:'',
        desc:"你可以听我的祝福吗？",
        trigger: function(res) { 
            this.imgUrl = userData_.headImgUrl;
            this.link = 'http://wxweb.ngrok.xiaomiqiu.cn/share.html?&unionId=' + userData_.unionId +'&headImgUrl=' + userData_.headImgUrl + '&voiceId=' + server + '?&';
            $('#chance-num').find('span').html(countNum);
        },
        success:function(){
            window.location.href = 'http://wxweb.ngrok.xiaomiqiu.cn/';
            if(userData_.shareClickNum == 0){
                $.ajax({
                    url:'http://wxapi.ngrok.xiaomiqiu.cn/open/lottery_add_one?unionId=' + userData_.unionId,
                    type:'get',
                    success:function(res){
                        // alert('分享次数加一！')
                    }
                })
            }
        }
    }
    wx.ready(function(){
        // alert('链接微信成功！标识：33');
        wx.onMenuShareTimeline(wxShareConfig);  //分享到朋友圈
        wx.onMenuShareAppMessage(wxShareConfig); //分享到微信朋友
        wx.onMenuShareQQ(wxShareConfig); //分享到QQ
        wx.onMenuShareQZone(wxShareConfig); //分享到QQ空间
        wx.checkJsApi({
        jsApiList: ['startRecord','translateVoice','stopRecord','stopVoice','downloadVoice','onVoicePlayEnd',
                    'uploadVoice','playVoice','onMenuShareTimeline','onMenuShareAppMessage',
                    'onMenuShareQZone','onMenuShareQQ','onMenuShareWeibo'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
        success: function(res) {
            // alert(JSON.stringify(res.checkResult));
        }
        });
        
        //获取用户录音功能权限
        wx.startRecord({
            success: function (res) {
                // alert('1111111')
                wx.stopRecord({
                    success: function (res) {}
                });
            }
        });
        
        $.ajax({
            url:'http://wxapi.ngrok.xiaomiqiu.cn/open/list_voice',
            type:'get',
            success:function(res){
                console.log('获取录音serverId:',res);
                var otherData = res.data;
                    if(!!otherData){
                        for (var i = 0; i < otherData.length; ++i) {
                            ;(function(i_){
                                $($('.user-head')[i_]).attr('src',otherData[i_].headImgUrl);
                                $($('.play')[i_]).attr('data-voice',otherData[i_].voiceId);
                            })(i);
                        }
                    }
                
            }
        });
    });
})();

// 分享祝福
$('.share,.modal-share-box').on('click',function(event){
    event.preventDefault();
    stopBubble();
    if(isWeiXin()){
        $('.cover-hint').show();
    }else{
        hintModal('请在微信中打开链接')
    }
});
$('.cover-hint').on('click',function(event){
    event.preventDefault();
    stopBubble();
    $(this).hide();
});

//录音控制模块
(function(){
    $('#tree-animation').hide();
    // 停止录音控制
    var endRecordVoice = function(){
        wx.stopRecord({
          success: function (res) {
            voice = res.localId;
            console.log('录音结束……');
            $('.voice-gif').hide();
            // 切换为摇奖按钮
            $('#affirm').css('display','inline-block');
            //划出底部确认框
            $('.buttom-affrim-box').slideDown();
            //录音ID绑定
            $('#current-user').attr('data-voice',voice);
          },
          fail: function (res) {
            console.log('录音结束错误：',res)
          }
        });
    };
    //按下开始录音
    $('#talkBtn').on('touchstart', function(event){
        event.preventDefault();
        stopBubble();
        if(isWeiXin() && countNum != 0){
            START = new Date().getTime();
            recordTimer = setTimeout(function(){
                wx.startRecord({
                    success: function(){
                        $('.voice-gif').show();
                        console.log('开始录音……')
                    },
                    cancel: function () {
                        alert('用户拒绝授权录音');
                    }
                });
            },300); 
            endVoice = setTimeout(function(){
               endRecordVoice();
            },30000)
        }else{
            if(isWeiXin() == false){
                alert('请在微信中打开！');
            }else{
                if(countNum == 0 && userData_.shareClickNum != 0){
                    hintModal('今日抽奖机会已用完<br/>明日请早，圣诞快乐！');
                }else if(countNum == 0 && userData_.shareClickNum == 0){
                    hintModal('摇奖机会已用完，分享祝福获得更多机会！');
                }
            }
        }
        return false;
    });

    $('#talkBtn').on('touchend', function(event){
        event.preventDefault();
        stopBubble();
        $('.voice-gif').hide();
        if(isWeiXin() && countNum != 0){
            END = new Date().getTime();
            console.log(END - START);
            if((END - START) < 300){
                END = 0;
                START = 0;
                hintModal('录音时间太短！')
                //小于300ms，不录音
                clearTimeout(recordTimer);
                clearTimeout(endVoice);
            }else if(300 < (END - START) < 29999){
                clearTimeout(recordTimer);
                clearTimeout(endVoice);
                endRecordVoice();
            }else{
                // hintModal('录音时间超过30秒！')
            }
        }else{
            // alert('请在微信中打开！');
        }
        return false;
    });
    
    //录音取消返回
    $('.back').on('click',function(){
        $(this).parent().slideUp();
    });

    $(function(){
        //录音确认
        $('.affrim').on('click',function(){
            $(this).parent().slideUp();
            uploadVoice();
        });
    });


    $('.modal-box').on('click',function(event){
        event.preventDefault();
        $(this).hide(); 
    });

     //点击摇奖
    $('#draw-lottery').on('click',function(event){
        event.preventDefault();
        stopBubble();
        if(countNum != 0){
            $('.modal-box').show();
            //点击摇奖过后抽取奖品
            getGift();
        }else{
            $('.modal-box').show().find('.modal-content').html('&nbsp&nbsp&nbsp&nbsp摇奖机会已用完，<br/>分享祝福获得更多机会！')
        }
    });
})();

// 底部获奖轮播
(function(){
    var loopDiv = $('.loop-box');
    var loopChild = $('.loop-box div:first-child')
    var po = 0;
    var timeMachine = setInterval(function(){
        po--;
        loopDiv.css('left',po + 'px');
        var testNum = po / -185;
        // var re = /^[1-9]+[0-9]*]*$/;
        if(po == -555){
           po = 0;
        }
    },20)
})();

//礼物touch放大
$('.gifts-box > img').click(function(event){
    event.preventDefault();
    stopBubble();
    if($(this).css('transform') == 'none'){
        $(this).css({'transform':'scale(2)','z-index':'20'});
    }else{
        if($(this).css('transform') == 'matrix(1, 0, 0, 1, 0, 0)'){
        $(this).css({'transform':'scale(2)','z-index':'20'});
        }
        if($(this).css('transform') == 'matrix(2, 0, 0, 2, 0, 0)'){
            $(this).css({'transform':'scale(1)','z-index':'11'});
        }
    }
    

});

(function(){
    //恢复按钮状态
    var renewPlayBtn = function(){
        $('.stop').hide();
        $('#current-user-stop').hide();
        $('.play').show();
        $('#current-user').show();
    };

    var playVoice = function(id){
        console.log('播放语音……')
        // ##播放语音接口
        wx.playVoice({
           localId: id, // 需要播放的音频的本地ID，由stopRecord接口获得
           success:function(res){
                wx.onVoicePlayEnd({
                    success: function (res) {
                    var localId = res.localId; // 返回音频的本地ID
                    renewPlayBtn();
                }
              });
           }
        });
    }

    var stopVoice = function(id){
        console.log(id);
        wx.stopVoice({
            localId: id // 需要停止的音频的本地ID，由stopRecord接口获得
        });
    }
    //播放当前用户录音
    $('#current-user').on('click',function(event){
        stopBubble();
        event.preventDefault();
        var e  = $(event.target);
        if(isWeiXin()){
            renewPlayBtn();
            e.hide();
            $('#current-user-stop').show();
            playVoice(e.attr('data-voice'));
        }else{
            alert('请在微信中打开！')
        }
    });
    //停止播放
    $('#current-user-stop').on('click',function(event){
        stopBubble();
        $(event.target).hide();
        $('#current-user').show();
        stopVoice($('#current-user').attr('data-voice'))
    });

    // 其他用户
    $('.play').on('click',function(event){
        var e  = $(event.target);
        event.preventDefault();
        stopBubble();
        var serverId = $(event.target).attr('data-voice');
         wx.downloadVoice({
            serverId: serverId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
                var localId = res.localId;// 返回音频的本地ID
                playVoice(localId);
                renewPlayBtn();
                e.hide();
                e.parent().find('.stop').show();
                $('.stop').on('click',function(event){
                    event.preventDefault();
                    stopBubble();
                    var e  = $(event.target);
                    e.hide();
                    e.parent().find('.play').show();
                    stopVoice(localId);
                });
            }
        });
    });
})();



// 分享祝福与我的礼物
(function(){
    $('.my-gift').on('click',function(event){
        event.preventDefault();
        $('.my-gift-page').slideDown();
        $.ajax({
            type:'get',
            url:'http://wxapi.ngrok.xiaomiqiu.cn/open/prize_list?unionId=' + userData_.unionId,
            success:function(res){
                var mygifts = res.data;
                console.log('我的礼物：',res.data);
                for (var i = mygifts.length - 1; i >= 0; i--) {
                    if(mygifts[i].prizeValue != 0){
                        var text = '<div>往往' +  mygifts[i].prizeValue +'钻值1份</div>';
                    }else{
                        var text = '<div>' +  mygifts[i].prizeName +'</div>';
                    };
                    $('#myGifts').append(text);
                }
            }
        });
    });
    $('.back-home').on('click',function(event){
        event.preventDefault();
        $('.my-gift-page').slideUp();
        $('.rule-page').slideUp();
    });

    //规则
    $('.rule').on('click',function(event){
        event.preventDefault();
        $('.rule-page').slideDown();
    })
})();

(function(){
    $('#dot').on('click',function(event){
        event.preventDefault();
        stopBubble();
        if(isIos()){
            window.location.href = 'https://itunes.apple.com/us/app/fa-bu-ce-shi/id1234471113?l=zh&ls=1&mt=8';
        }
        if(isAndroid()){
            window.location.href = 'http://shouji.baidu.com/software/22188500.html';
        }
    })
})();










